package com.begamer.card.controller;

import java.io.PrintWriter;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.begamer.card.common.CommParams;
import com.begamer.card.common.dao.hibernate.CommDao;
import com.begamer.card.common.util.MD5;
import com.begamer.card.common.util.StringUtil;
import com.begamer.card.common.util.binRead.RechargeData;
import com.begamer.card.json.PayExtraJson;
import com.begamer.card.log.ErrorLogger;
import com.begamer.card.log.MemLogger;
import com.begamer.card.model.pojo.PayInfo;
import com.begamer.card.model.pojo.PayOrder;

public class PayBddkController extends AbstractMultiActionController
{
	
	private static final Logger memlogger=MemLogger.logger;
	private static final Logger errorlogger=ErrorLogger.logger;
	@Autowired
	private CommDao commDao;
	
	//==百度多酷==//
	//http://114.215.183.102:8080/card_server_pay/pay.htm?action=pay_bddk
	public ModelAndView pay_bddk(HttpServletRequest request,HttpServletResponse response)
	{
		String amount=request.getParameter("amount");//充值成功的金额(单位:按汇率结算后的元), 汇率请参看附表
		String cardtype=request.getParameter("cardtype");//充值类型(参见附表)
		String orderid=request.getParameter("orderid");//订单号(如cp未提供订单号,则传入百度移劢游戏订单号)
		String result=request.getParameter("result");//充值结果(1:成功, 2:失败)
		String timetamp=request.getParameter("timetamp");//订单完成时的unix时间戳
		String aid=request.getParameter("aid");//将客户端传入的aid原样传回
		String client_secret=request.getParameter("client_secret");//将以上6个参数不后台注册分配给cp的应用secret按下列顺序组成串进行MD5加密后字母转换成小写：(PHP示例代码) $aid=urlencode($aid); $client_secret=strtolower(md5($amount$cardtype$orderid$result$timetamp$AppSecret$aid));
		
		String returnString="ERROR_SIGN";
		if(aid==null)
		{
			memlogger.info("本次消费信息(bddk)参数错误");
			returnString="ERROR_FAIL";
			// 返回response
			PrintWriter out = null;
			try
			{
				response.setContentType("text/html;charset=UTF-8");
				out=response.getWriter();
				out.println(returnString);
				out.flush();
			}
			catch (Exception e2)
			{
				errorlogger.error("返回信息出错", e2);
			}
			finally
			{
				out.close();
			}
			return null;
		}
		else
		{
			try
			{
				aid=URLEncoder.encode(aid,"UTF-8");
			}
			catch (Exception e)
			{
				errorlogger.error("获取aid出错",e);
			}
		}
		//md5($amount$cardtype$orderid$result$timetamp$AppSecret$aid));
		String s=amount+cardtype+orderid+result+timetamp+CommParams.getInstance().getPay_key_bddk()+aid;
		memlogger.info("本次消费信息(bddk)s:"+s);
		memlogger.info("本次消费信息(bddk)client_secret:"+client_secret);
		String sign=MD5.md5(s).toLowerCase();
		//验证成功
		if(client_secret.equals(sign))
		{
			//更新订单信息
			PayOrder po=null;
			try
			{
				po=commDao.getPayOrder(StringUtil.getInt(orderid));
				if(po==null)
				{
					errorlogger.error("没有这个订单:"+StringUtil.getInt(orderid));
				}
				else
				{
					po.setStatus(1);
					commDao.saveOrUpdate(po);
				}
			}
			catch (Exception e)
			{
				errorlogger.error("更新订单信息出错", e);
			}
			//保存支付信息
			String serverId="";
			String extraData=null;
			PayInfo pi=null;
			try
			{
				if(po!=null)
				{
					extraData=po.getExtra();
					serverId=po.getServerId();
				}
				//保存支付记录
				pi=PayInfo.createPayInfo(null, StringUtil.getDateTime(System.currentTimeMillis()), "1", amount, extraData, serverId, orderid, orderid);
				commDao.save(pi);
			}
			catch (Exception e)
			{
				errorlogger.error("保存支付信息出错", e);
			}
			//通知游戏服务器
			try
			{
				if(extraData!=null)
				{
					PayExtraJson pej=JSON.toJavaObject(JSON.parseObject(extraData), PayExtraJson.class);
					RechargeData rData =RechargeData.getRechargeData(pej.rechargeId);
					if(rData.cost ==StringUtil.getInt(amount))
					{
						PayController.notifyGameServer(serverId,pej.playerId+"",pej.rechargeId+"",amount);
					}
					else
					{
						memlogger.info("玩家非法充值：支付"+amount+"应该"+rData.cost);
					}
					
				}
			}
			catch (Exception e)
			{
				errorlogger.error("通知游戏服务器出错", e);
			}
			//通知talkingdata
			PayController.notifyTalkingData(pi);
			returnString="SUCCESS";
		}
		//验证失败
		else
		{
			memlogger.info("bddk验证失败");
		}
		
		// 返回response
		PrintWriter out = null;
		try
		{
			response.setContentType("text/html;charset=UTF-8");
			out=response.getWriter();
			out.println(returnString);
			out.flush();
		}
		catch (Exception e)
		{
			errorlogger.error("返回信息出错", e);
		}
		finally
		{
			out.close();
		}
		return null;
	}
	
	public static void main(String[] args)
	{
		String aid="{\"username\":\"BD_3858939479\",\"playerId\":5265,\"rechargeId\":2,\"os\":\"android\"}";
		try
		{
			aid=URLEncoder.encode(aid,"UTF-8");
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		
		String s="110116311408174113wden1PlF64FxuzPqhG0oCw8OexLZWq2M"+aid;
		String sign=MD5.md5(s).toLowerCase();
		if("b99a66e1f53de404cbd37c7402a85fc0".equals(sign))
		{
			System.out.println("OK");
		}
	}
	
}
